package com.example.flower_shop.controller;

import com.example.flower_shop.common.ApiResponse;
import com.example.flower_shop.dto.cart.AddToCartRequest;
import com.example.flower_shop.dto.cart.CartItemVO;
import com.example.flower_shop.dto.cart.UpdateCartRequest;
import com.example.flower_shop.entity.CartItem;
import com.example.flower_shop.entity.User;
import com.example.flower_shop.exception.BusinessException;
import com.example.flower_shop.service.CartService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "购物车管理")
@Validated
@RestController
@RequestMapping("/api/cart")
@RequiredArgsConstructor
@Slf4j
public class CartController {

    private final CartService cartService;

    private Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || authentication.getPrincipal() == null) {
            log.error("用户未登录");
            throw new BusinessException("USER_NOT_AUTHENTICATED", "用户未登录");
        }
        try {
            return (Long) authentication.getPrincipal();
        } catch (Exception e) {
            log.error("无法获取用户ID: {}", e.getMessage());
            throw new BusinessException("USER_NOT_AUTHENTICATED", "无法获取用户信息");
        }
    }

    @ApiOperation("获取购物车列表")
    @GetMapping
    public ApiResponse<List<CartItemVO>> getCart() {
        Long userId = getCurrentUserId();
        log.info("获取购物车列表 - 用户ID: {}", userId);
        List<CartItem> cartItems = cartService.findByUserId(userId);
        List<CartItemVO> cartItemVOs = cartItems.stream()
                .map(CartItemVO::new)
                .collect(Collectors.toList());
        return ApiResponse.success(cartItemVOs);
    }

    @ApiOperation("添加商品到购物车")
    @PostMapping
    public ApiResponse<CartItemVO> addToCart(
            @ApiParam("添加购物车请求") @Valid @RequestBody AddToCartRequest request) {
        Long userId = getCurrentUserId();
        log.info("添加商品到购物车 - 用户ID: {}, 请求数据: {}", userId, request);
        CartItem cartItem = cartService.addToCart(userId, request.getProductId(), request.getQuantity());
        log.info("添加购物车成功 - 用户ID: {}, 商品ID: {}, 数量: {}", userId, request.getProductId(), request.getQuantity());
        return ApiResponse.success(new CartItemVO(cartItem));
    }

    @ApiOperation("更新购物车商品数量")
    @PutMapping
    public ApiResponse<CartItemVO> updateCart(
            @ApiParam("更新购物车请求") @Valid @RequestBody UpdateCartRequest request) {
        Long userId = getCurrentUserId();
        log.info("更新购物车商品数量 - 用户ID: {}, 请求数据: {}", userId, request);
        CartItem cartItem = cartService.updateQuantity(userId, request.getProductId(), request.getQuantity());
        return ApiResponse.success(new CartItemVO(cartItem));
    }

    @ApiOperation("从购物车移除商品")
    @DeleteMapping("/{cartItemId}")
    public ApiResponse<Void> removeFromCart(
            @ApiParam("购物车项ID") @PathVariable Long cartItemId) {
        Long userId = getCurrentUserId();
        log.info("从购物车移除商品 - 用户ID: {}, 购物车项ID: {}", userId, cartItemId);
        cartService.removeFromCart(userId, cartItemId);
        return ApiResponse.success(null);
    }

    @ApiOperation("清空购物车")
    @DeleteMapping
    public ApiResponse<Void> clearCart() {
        Long userId = getCurrentUserId();
        log.info("清空购物车 - 用户ID: {}", userId);
        cartService.clearCart(userId);
        return ApiResponse.success(null);
    }

    @ApiOperation("获取购物车商品数量")
    @GetMapping("/count")
    public ApiResponse<Integer> getCartItemCount() {
        Long userId = getCurrentUserId();
        log.info("获取购物车商品数量 - 用户ID: {}", userId);
        int count = cartService.countByUserId(userId);
        return ApiResponse.success(count);
    }

    @ApiOperation("检查并更新购物车商品状态")
    @PostMapping("/check")
    public ApiResponse<List<CartItemVO>> checkAndUpdateCart() {
        Long userId = getCurrentUserId();
        log.info("检查并更新购物车商品状态 - 用户ID: {}", userId);
        cartService.checkAndUpdateCartItems(userId);
        List<CartItem> cartItems = cartService.findByUserId(userId);
        List<CartItemVO> cartItemVOs = cartItems.stream()
                .map(CartItemVO::new)
                .collect(Collectors.toList());
        return ApiResponse.success(cartItemVOs);
    }

    @ApiOperation("根据商品ID批量移除购物车商品")
    @DeleteMapping("/removeItems")
    public ApiResponse<Void> removeItemsFromCart(@ApiParam("商品ID列表") @RequestBody List<Long> productIds) {
        Long userId = getCurrentUserId();
        log.info("批量移除购物车商品 - 用户ID: {}, 商品ID列表: {}", userId, productIds);

        if (productIds == null || productIds.isEmpty()) {
            return ApiResponse.success(null);
        }

        // 对每个商品ID，找到对应的购物车项并删除
        for (Long productId : productIds) {
            cartService.findByUserId(userId).stream()
                    .filter(item -> item.getProduct().getId().equals(productId))
                    .findFirst()
                    .ifPresent(cartItem -> cartService.removeFromCart(userId, cartItem.getId()));
        }

        return ApiResponse.success(null);
    }
}